package unitest02

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"syscall"
)

type Monster struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Skill string `json:"skill"`
}

// Store
//
//	@Description: 将结构体序列化后写入文件
//	@receiver m
//	@param path
//	@return bool
func (m *Monster) Store(path string) bool {
	bytes, err := json.Marshal(*m)
	if err != nil {
		fmt.Println("bytes marshal err=-", err)
		return false
	}
	file, err := os.OpenFile(path, syscall.O_RDONLY|syscall.O_CREAT, 0666)
	if err != nil {
		fmt.Println("openFile err =", err)
		return false
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			fmt.Println("close file err=", err)
		}
	}(file)
	writer := bufio.NewWriter(file)
	_, err = writer.WriteString(string(bytes) + "\r\n")
	if err != nil {
		return false
	}
	err = writer.Flush()
	if err != nil {
		return false
	}
	return true

}

// ReStore
//
//	@Description: 从文件中反序列化数据
//	@receiver m
//	@param path
//	@return *Monster
func (m *Monster) ReStore(path string) *Monster {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("open file err=", err)
		return nil
	}
	err = json.Unmarshal(bytes, m)
	if err != nil {
		fmt.Println("json unmarshal err=", err)
		return nil
	}
	return m

}
